'''
Created on Jun 11, 2011

@author: Igor
'''
from lib.dbobjects import Explanation, Athlete, RESULTS_DISPLAYED

def cpc_top_athletes(stats):
    explanation = Explanation.all().get()
    explanation.title="This auction is based purely" + \
            " on CPC value, whoever pays us more" + \
            " per click gets better placement"
    ids = []
    names = []
    cpcs = []
    athletes = Athlete.all().filter('out_of_budget =', False).order('-cpc').fetch(RESULTS_DISPLAYED)
    i = 1
    comments = []
    for athlete in athletes:
        if i == RESULTS_DISPLAYED:
            comments.append("The athlete in position %d has a CPC of %d.  " %
                (i, athlete.cpc))
        else:
            comments.append("The athlete in position %d has a CPC of %d." %
                    (i, athlete.cpc) + "  Formula: (CPC of athlete in position" +
                    " %d) + 1." % (i+1))
        ids.append(athlete.id)
        names.append(athlete.name)
        cpcs.append(athlete.cpc)
        i += 1
    names.append("None of these")
    
    costs = RESULTS_DISPLAYED * [0]
    for i in xrange(RESULTS_DISPLAYED):
        current_index = RESULTS_DISPLAYED - 1 - i
        if current_index == RESULTS_DISPLAYED - 1:
            costs[current_index] = cpcs[current_index]
            comments[current_index] += "  Since he is last, the athlete will" + \
                    " pay max CPC of %d." % (costs[current_index])
            stats.max_cpc_times += 1
        else:
            costs[current_index] = cpcs[current_index+1] + 1
            if costs[current_index] >= cpcs[current_index]:
                costs[current_index] = cpcs[current_index]
                comments[current_index] += "  The athlete will pay his maximum CPC of %d" % \
                (costs[current_index])
                stats.max_cpc_times += 1
            else:
                comments[current_index] += "  The athlete will pay %d" % costs[current_index]
    explanation.comments = comments
    explanation.put()
    stats.top_names = names
    stats.costs = costs
    return ids